//
//  BaseConnection.swift
//  MySwiftObject
//
//  Created by anscen on 2022/3/8.
//  Copyright © 2022 wangws1990. All rights reserved.
//

import UIKit
import SQLite.Swift
import RealmSwift
public let dataBase = BaseConnection.manager
public class BaseConnection{
    public static let manager = BaseConnection()
    public lazy var db: Connection? = {
        guard let url = self.path else { return nil }
        var db = try? Connection(url)
        db?.busyTimeout = 5.0//设置线程安全
        return db
    }()
    //MARK:表是否包含某一列
    public class func haveColumn(_ tableName :String,column :String) -> Bool{
        guard let db = dataBase.db else { return false }
        guard let query = try? db.prepare("PRAGMA table_info(" + tableName + ")" ) else { return false }
        let listData = ArraySlice(query).filter { objc in
            if objc.count > 1 {
                if let row = objc[1] as? String{
                    return row == column
                }
            }
            return false
        }
        return listData.count > 0 ? true : false
    }
    fileprivate lazy var path : String? = {
        let path = NSHomeDirectory() + "/Documents/Caches/Sqlite/"
        let file = FileManager.default
        if file.fileExists(atPath: path) == false{
            guard let _ = try? file.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil) else { return nil }
        }
        
        return path + "DataBase.sqlite"
    }()
}
            
